import { defineStore } from 'pinia'
import router from '@/router'
import { RoutesType } from '@/store/modules/routes/type'
import { RouteRecordRaw } from 'vue-router'
import { lStorage } from '@/utils/storage'

// 自动注册全局组件（懒加载模式）
const modules = import.meta.glob('../../../views/**/*.vue')

export const useRoutesStore = defineStore('routes', {
	state: () => ({
		routes: [] as RoutesType[], // 动态路由存储
		addedRouteNames: [] as string[], // 已添加的路由名称
	}),
	actions: {
		/**
		 * 动态添加路由
		 * @param data 动态路由数据
		 */
		async addRoutes(data: RoutesType[]) {
			// 每次调用都更新本地存储和状态
			lStorage.set('WX_USER_ROUTES', data)
			this.routes = data

			// 清理之前添加的路由
			this.addedRouteNames.forEach(
				(name) => router.hasRoute(name) && router.removeRoute(name)
			)
			this.addedRouteNames = []

			/**
			 * 递归解析动态路由
			 * @returns 解析后的路由数组和收集的路由名称
			 */
			const parseRoutes = (
				routesData: RoutesType[]
			): { routes: RouteRecordRaw[]; names: string[] } => {
				const addedNames: string[] = []

				const parsed = routesData
					.map((item) => {
						// 处理组件路径（支持三种形式：）
						// 1. 直接传入组件函数 () => import()
						// 2. 字符串路径 '/path'
						// 3. 完整路径 'src/views/path.vue'
						let componentLoader: (() => Promise<any>) | undefined

						if (typeof item.component === 'function') {
							// 情况1：已经是动态导入函数
							componentLoader = item.component as () => Promise<any>
						} else if (typeof item.component === 'string') {
							// 处理路径字符串
							const normalizedPath = (item.component as string).startsWith('/')
								? `../../../views${item.component}.vue`
								: `../../../views/${item.component}.vue`

							// 情况2/3：从模块映射中获取
							componentLoader = modules[normalizedPath]
						}

						// 检查组件有效性（允许无组件但有子路由的情况）
						if (!componentLoader && !item.children?.length) {
							console.warn(`路由组件未找到: ${item.path} -> ${item.component}`)
							return null
						}

						// 处理子路由
						const childrenResult = item.children
							? parseRoutes(item.children)
							: null
						if (childrenResult && childrenResult.routes.length === 0)
							return null

						// 收集路由名称
						if (item.name) addedNames.push(item?.name as any)

						// 构造路由对象
						return {
							...item,
							component: componentLoader
								? () =>
										componentLoader!().catch(
											() => import('@/page/error/404.vue')
										)
								: undefined,
							children: childrenResult?.routes,
						} as RouteRecordRaw
					})
					.filter(Boolean) as RouteRecordRaw[]

				return { routes: parsed, names: addedNames }
			}

			// 解析路由并记录名称
			const { routes: parsedRoutes, names } = parseRoutes(data)
			this.addedRouteNames = names

			// 添加动态路由到父路由下
			parsedRoutes.forEach((route) => {
				router.addRoute('layout', route)
			})

			// 添加全局404路由（确保最后添加）
			if (!router.hasRoute('not-found')) {
				router.addRoute({
					path: '/:pathMatch(.*)*',
					name: 'not-found',
					component: () => import('@/page/error/404.vue'),
				})
			}
		},

		/**
		 * 清除动态路由
		 */
		clearRoutes() {
			// 移除所有已添加路由
			this.addedRouteNames.forEach(
				(name) => router.hasRoute(name) && router.removeRoute(name)
			)
			this.addedRouteNames = []

			// 清理状态和存储
			this.routes = []
			lStorage.remove('WX_USER_ROUTES')
		},
	},
})
